package likouJava;

public class 回文链表 {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null){
            return true;
        }

        //使用快慢指针找到中点
        ListNode slow = head;
        ListNode fast =head;

        while (fast.next !=null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        //反转后半部分链表
        ListNode secondHalf = reverseList(slow.next);

        //比较前一部分和后一部分
        ListNode fistHalf = head;
        boolean isPalindrome = true;

        while (secondHalf != null){
            if (fistHalf.val != secondHalf.val){
                isPalindrome = false;
                break;
            }
            fistHalf = fistHalf.next;
            secondHalf = secondHalf.next;
        }
        return isPalindrome;

    }
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null){
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

}
